const express = require('express');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const User = require('../models/User');
const auth = require('../middleware/auth');

// 获取个人信息
router.get('/profile', auth, async (req, res) => {
    try {
        const user = await User.findById(req.user._id).select('-password');
        res.json(user);
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

// 更新个人信息
router.put('/profile', auth, [
    body('username').optional().trim().notEmpty().withMessage('用户名不能为空'),
    body('bio').optional().trim(),
    body('avatar').optional().trim()
], async (req, res) => {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { username, bio, avatar } = req.body;
        const updates = {};

        if (username) updates.username = username;
        if (bio !== undefined) updates.bio = bio;
        if (avatar) updates.avatar = avatar;

        const user = await User.findByIdAndUpdate(
            req.user._id,
            { $set: updates },
            { new: true }
        ).select('-password');

        res.json(user);
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取用户文章列表
router.get('/:userId/articles', async (req, res) => {
    try {
        const { page = 1, limit = 10 } = req.query;
        const articles = await Article.find({ author: req.params.userId })
            .populate('author', 'username avatar')
            .sort({ createdAt: -1 })
            .limit(limit * 1)
            .skip((page - 1) * limit);

        const count = await Article.countDocuments({ author: req.params.userId });

        res.json({
            articles,
            totalPages: Math.ceil(count / limit),
            currentPage: page
        });
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

module.exports = router; 